﻿using System;
using System.Configuration;
using System.Threading;
using KJFramework.Helpers;

namespace KJFramework.Tracing
{
    public enum TracingLevel { Info = 0, Warn = 1, Error = 2, Crtitical = 3 }

    public static class TracingSettings
    {
		/// <summary>
		///   Added a constructor that can anlayses currently config file.
		/// </summary>
		static TracingSettings()
		{
			string configPath = MonoRuntimeHelper.GetCurrentConfigFilePath();
			Console.WriteLine("Platform: " + Environment.OSVersion.Platform);
            Console.WriteLine("#Currently config file path: " + configPath);
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configPath };
			_config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
			Console.WriteLine ("#_config Null state: " + _config == null);
			if(_config != null)
			{
				Console.WriteLine ("#config app-settings count: " + _config.AppSettings.Settings.Count);
				Console.WriteLine ("#config sections count: " + _config.Sections.Count);
				Console.WriteLine ("#config inner nodes count: " + _config.AppSettings.Settings.Count);
			}
		}

        private const string Section = "Tracing";

        private static int _version;
        private static Action _handler;
		private static Configuration _config;

        internal static void WatchProviderChange(Action handler)
        {
            _handler = handler;
        }

        private static void OnTracingProviderChanged(int version, string section, string name)
        {
            if (Interlocked.Exchange(ref _version, version) != version)
                _handler();
        }

        public static TracingLevel Level
        {
			get { return (TracingLevel)Enum.Parse(typeof(TracingLevel), _config.AppSettings.Settings["Tracing-Level"].Value); }
        }

        public static string Provider
        {
			get { return _config.AppSettings.Settings["Tracing-Provider"].Value; }
        }

        public static string Datasource
        {
            get
            {
                return (Environment.OSVersion.Platform == PlatformID.Unix
                           ? _config.AppSettings.Settings["Tracing-Datasource"].Value
                           : _config.AppSettings.Settings["Tracing-Datasource-Win32"].Value);
            }
        }
    }
}
